/**
 * 114. 二叉树展开为链表
 * https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/
 */
const { createTreeNode } = require('../../libs/public');

/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
function flatten(root) {
  if (!root) return;
  const stack = [];
  let lastNode = root;
  if (root.right) stack.push(root.right);
  if (root.left) stack.push(root.left);
  while (stack.length) {
    const node = stack.pop();
    lastNode.left = null;
    lastNode.right = node;
    lastNode = node;
    if (node.right) stack.push(node.right);
    if (node.left) stack.push(node.left);
  }
}

let root;

root = createTreeNode([1, 2, 5, 3, 4, null, 6]);
flatten(root);
console.log(JSON.stringify(root, null, 2));

root = createTreeNode([]);
flatten(root);
console.log(JSON.stringify(root, null, 2));

root = createTreeNode([1]);
flatten(root);
console.log(JSON.stringify(root, null, 2));
